package com.chexiehui.jc.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.FragmentViewPagerAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpLazyLoadFragment;
import com.chexiehui.jc.entity.ForumInfo;
import com.chexiehui.jc.event.GlobalFollowForumEvent;
import com.chexiehui.jc.mvp.forum.ForumFollowHomeCovenant;
import com.chexiehui.jc.mvp.forum.ForumFollowHomePresenter;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.widget.CircleImageView;
import com.chexiehui.jc.widget.LoadingLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description: 关注的论坛主页
 */

public class ForumFollowHomeFragment extends BaseMvpLazyLoadFragment<ForumFollowHomePresenter> implements ForumFollowHomeCovenant.View{
    @BindView(R.id.rtv_forum_count)
    RadiusTextView rtvForumCount;
    @BindView(R.id.rtv_forum_join)
    RadiusTextView rtvForumJoin;
    @BindView(R.id.tv_forum_introduce)
    TextView tvForumIntroduce;

    public static ForumFollowHomeFragment getInstance(String forumId) {
        ForumFollowHomeFragment fragment = new ForumFollowHomeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("forumId", forumId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @BindView(R.id.ll_user_head_container)
    LinearLayout llUserHeadContainer;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.stl_action_table)
    SlidingTabLayout stl_action_table;
    @BindView(R.id.vp_action_pager)
    ViewPager vp_action_pager;
    private ForumInfo forumInfo;
    private String forumId;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            forumId = bundle.getString("forumId");
        }
    }

    private String[] titles = new String[]{"动态", "精华"};
    private ArrayList<Fragment> actionFragmentList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_forum_follow_home;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        loadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                lazyLoad();
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(1000, true);
                ((ForumFollowHomeBbsFragment) actionFragmentList.get(vp_action_pager.getCurrentItem()))
                        .onParentPageCallRefresh();
            }
        });
        isPrepared = true;
        if (StringUtils.isTrimEmpty(forumId)) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("没有找到任何数据");
        } else {
            loadingLayout.setStatus(LoadingLayout.Loading);
            lazyLoad();
        }
    }

    private void setContentPageInfo() {
        vp_action_pager.setOffscreenPageLimit(titles.length);
        for (int i = 0; i < titles.length; i++) {
            actionFragmentList.add(ForumFollowHomeBbsFragment.getInstance(forumId, i));
        }
        vp_action_pager.setAdapter(new FragmentViewPagerAdapter(getChildFragmentManager(), actionFragmentList, titles));
        stl_action_table.setViewPager(vp_action_pager);
    }

    @Override
    protected void lazyLoad() {
        if (!isVisible || !isPrepared || mHasLoadedOnce) {
            return;
        }
        if (StringUtils.isTrimEmpty(forumId)) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("没有找到任何数据");
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getForumInfo();
    }

    @Override
    protected ForumFollowHomePresenter createPresenter() {
        return new ForumFollowHomePresenter(this);
    }

    private void setHeadForumInfo() {
        llUserHeadContainer.removeAllViews();
        for (int i = 0; i < forumInfo.getPhotoList().size(); i++) {
            ImageView ivHead = (ImageView) View.inflate(mActivity, R.layout.item_only_head, null);
            llUserHeadContainer.addView(ivHead);
            GlideUtil.loadImageViewCircleCrop(mActivity, forumInfo.getPhotoList().get(i),
                    ivHead, R.drawable.shape_circle, R.drawable.shape_circle);
        }
        rtvForumCount.setText(forumInfo.getFollowCount());
        rtvForumJoin.setSelected(forumInfo.isCollect());
        rtvForumJoin.setText(forumInfo.isCollect() ? "已加入" + forumInfo.getDay() + "天" : "加入");
        tvForumIntroduce.setText(forumInfo.getIntroduction());
    }

    @Override
    public void onGetForumInfoSuccess(BaseModel<ForumInfo> successResult) {
        mHasLoadedOnce = true;
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
        forumInfo = successResult.getData();
        setHeadForumInfo();
        if (actionFragmentList.size() <= 0) {
            setContentPageInfo();
        }
    }

    @Override
    public void onGetForumInfoFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            mHasLoadedOnce = true;
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public String getForumId() {
        return forumId;
    }

    @Override
    public void onDoFollowForumSuccess(BaseModel<String> successResult) {
        EventBus.getDefault().post(new GlobalFollowForumEvent(successResult.getData(), !forumInfo.isCollect()));
    }

    @Override
    public void onDoFollowForumFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Subscribe
    public void onGlobalFollowForumEvent(GlobalFollowForumEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getForumId())) {
            forumInfo.setCollect(event.isFollow());
            rtvForumJoin.setSelected(forumInfo.isCollect());
            rtvForumJoin.setText(forumInfo.isCollect() ? "已加入" + forumInfo.getDay() + "天" : "加入");
        }
    }

    @OnClick({R.id.rtv_forum_join})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.rtv_forum_join:
                mvpPresenter.doFollowForum(getForumId());
                break;
        }
    }

   /* @Override
    public void onClick(View v) {
        Integer tag = (Integer) v.getTag();
        if(tag != null){
            if(tag == -1){
                mvpPresenter.doFollowForum(getForumId());
            }
        }
    }*/
}
